<script setup>
/**
 * @name 数字人字幕生成
 */
import { reactive, computed, ref, nextTick, watch } from 'vue'
import request from "@/common/utils/request";
import {
  CaretDownOutlined,
  PlusOutlined,
  MinusOutlined,
  CheckOutlined,
  CaretUpOutlined,
  InfoCircleOutlined
} from "@ant-design/icons-vue";

import IdentifySubtitles from "@/views/shotstack/components/IdentifySubtitles/index.vue"

import utils from '@/common/utils/utils.js'

// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'
// 充值弹窗开关
const vipVisible = ref(false)

// 颜色选取
import ColorPicker from "colorpicker-v3";
import "colorpicker-v3/style.css";
import { message } from 'ant-design-vue';

// loading 遮罩
import loadingMask from '@/components/loadingMask/index.vue'
const loadingMaskRef = ref()

// 富文本
import editor from '@/views/shotstack/digitalHuman/AIdigitalHumanCreatVideo/Components/TextEditor/index.vue'
const editorRef = ref([])

const emit = defineEmits(['openSubtitleCreat'])

const getBaseFormData = () => {
  return {
    font_family: '',
    font_name: '',
    font_url: '',
    font_size: 52,
    font_path:'',
    // 字体颜色
    color: '#000000',
    bg_color: '',
    bold: 0,
    italic:0,
    alignment: "center",

    // 花字id
    flower_id: '',
    flower_type:'effectColor',// system 是我们自己的花字， 'effectColor' 表示是用的阿里云的
}
}

const formState = reactive(getBaseFormData())

// 拾色器默认颜色
const setColor = ref(formState.color);

const alignmentArr = [
  {
    id: 1,
    type: "left",
    icon: "icon-zuoduiqi",
  },
  {
    id: 2,
    type: "center",
    icon: "icon-juzhongduiqi",
  },
  {
    id: 3,
    type: "right",
    icon: "icon-youduiqi",
  },
];
const state = reactive({
    visible: false,
    // 系统花字列表
    flowerArr: [],
    // 阿里花字列表
    flowerAliArr: [],
    // 字体列表
    fontList:[],
    // 折叠样式
    isFlod: false,
    flower_type: 'effectColor',
    // 选择字体开关
  selectFontPop: false,
    // 编辑的 item
    detailItem: null,
    // 头部进度条
  current: 0,

  // 字幕编辑列表
  textList: [],
  // 字幕列表 基础数据, 用于重置时使用
  baseTextList: [],

  // 提交 需要的任务id
  job_id: '',
  //   [...Array(5)].map((ele, index) => {
  //   return {
  //     text: '字幕内容' + index,
  //     id: index,
  //   }
  // }),
  presetStylesList:[]
})

console.log(state.textList,'textListtextListtextList');


// 选择的字体
const selectFontcomputed = computed(() => {
    const find = state.fontList.find(ele =>  ele.font_family == formState.font_family)
    return find || {}
})

// 获取系统花字列表
const getFlowerListData = async () => {
      const presetStyles = await request.get(
        "/work_ai",
        "/user/shotstack/material/presetStyles/list"
    );
    state.presetStylesList = presetStyles
    state.flowerArr = presetStyles?.result;
    state.flowerAliArr = presetStyles?.resultEffect;

    const is_default = presetStyles?.resultEffect.find(
    (ele) => ele.is_default == 1
    );

  console.log(is_default, '默认的花字列表??');
    formState.flower_id = is_default?.id
    console.log(state,'列表状态??');
}

// 获取字体列表
const getFontList = async () => {
  const res = await  request.get("/work_ai", "/user/shotstack/material/fonts/list")
  res.result.map((item) => {
      item.label = item.name;
      item.value = item.material_url;
    });
    state.fontList = res.result;
    const find = state.fontList.find((item) => item.id_default == 1);

    let data = {
        font_name: find.name,
        font_path: find.material_path,
        font_style: find.font_style,
        font_family: find.font_family,
        font_url: find.material_url,
    }
    Object.assign(formState, data)

        res.result.forEach((font) => {
        const style = document.createElement("style");
        style.innerHTML = `
        @font-face {
        font-family: '${font.font_family}';
        src: url('${font.material_url}') format('truetype');
        }
    `;
        document.head.appendChild(style);
        
        });
}


// 获得对应项的字体样式
const getStyle = (item) => {
  // debugger
  return {
    color: item.fontcolor,
    "-webkit-text-stroke": item.bordercolor ? `1px ${item.bordercolor}` : "",
  };
};

const openType = ref('')
// 打开拾色器弹窗
const colorPickerClick = (type, ev) => {
  // debugger
  // 字体的颜色默认值为黑色, 背景色默认值为透明
    type == "font" ? (setColor.value = "#000000") : (setColor.value = "");
    // 存放打开的类型
    openType.value = type
  const target = ev.target;
  console.log(ev, "事件对象");
  // 获取元素的位置信息，getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置。
  const rect = target.getBoundingClientRect();
  // 计算元素右侧边缘到视口左侧的距离
  const dom = document.querySelector(".zs-color-picker-btn-color");
  dom.click();

  // 获取视口的宽度
  const viewportWidth = window.innerWidth;

  // 计算元素距离屏幕右侧的距离
  const rightDistanceToViewportLeft = rect.right;
  const rightDistanceToViewportRight = +(
    viewportWidth - rightDistanceToViewportLeft
  ).toFixed(0);
  const top = (rect.top + 30).toFixed(0);
  // 修改弹窗的位置为当前点击元素的位置下方
  const pickerDom = document.querySelector(".zs-color-picker-panel");
  pickerDom.style.position = "fixed";
  pickerDom.style.top = top + "px";
  pickerDom.style.right = rightDistanceToViewportRight + "px";
};

// 清除选择的背景色
const clearBgc = () => {
    formState.bg_color = "";
};

// 选择对齐方式
const selectAlignmentPop = (item) => {
  formState.alignment = item.type;
};

// 选择字体
const selectFont = (item) =>{
    // formState.font_family = item.font_family
    let data = {
        font_name: item.name,
        font_path: item.material_path,
        font_style: item.font_style,
        font_family: item.font_family,
        font_url: item.material_url,
    }
    Object.assign(formState, data)
}

// 取色器选择颜色
const colorChange = (e) => {
    console.log(e, "颜色改变");
    console.log(openType.value,'openType 打开的方式');
    
    if (openType.value == "font") {
    formState.color = e.hex
    } else if (openType.value == "bgc") {
        formState.bg_color = e.hex
        subTitle.value.bg_color = e.hex;
    }
};


// 修改字体粗细
const changeBold = () => {
  formState.bold == 1
    ? (formState.bold = 0)
    : (formState.bold = 1);
};

// 修改字体倾斜
const changeItalic = () => {
  formState.italic == 1
    ? (formState.italic = 0)
    : (formState.italic = 1);
};

// 选择花字
const selectFontStyle = (item) => {
    console.log(item, '选择的花字');
    if (formState.flower_id == item.id) {
        formState.flower_id = ''
        return
    }
    formState.flower_id = item.id
}

const submitLoading = ref(false)

const successData=ref(false)
const successDataResult =ref({})
// 提交
const handleOk = async (data) => {  
  successData.value = !successData.value
}

const successChange= async (data) => {  
    if(!state.detailItem.id) return message.warn('缺少数字人合成视频id')
    setTimeout(async ()=>{
      if(Object.keys(data).length){
        submitLoading.value = true
        let params = data
        // 匹配大部分emoji的正则表达式（持续更新版本）
        const emojiRegex = /[\u{1F300}-\u{1F5FF}\u{1F600}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{FE00}-\u{FE0F}]/gu;
        if(state.job_id){
          params.job_id = state.job_id
        }

        try {
            // 点数消耗校验
            await pointConsumption()
            
            console.log(params, '即将提交的数据');

            const uniqueIdRes = await request.get("/work_ai", "/user/platform/uniqueId")
            params.unique_id = uniqueIdRes.uniqueId
            const res = await request.post("/work_ai","/human/video/aiAsr/upSubmitMedia",params);    
            console.log(res,'生成字幕视频提交结果');
            if(res?.code && res?.code != 1000) return message.error(res?.msg || '提交失败!')
            message.success('提交成功!')
            close()
            // 打开 数字人生成字幕 tab
            emit('openSubtitleCreat')
        } finally {
          submitLoading.value = false
        }
      }
    },20)
}


// 点数信息
const countData = ref(null)
// 点数消耗查询
const pointConsumption = (number = 1) => {

return new Promise(async(resolve, reject) => {
  const res = await request.get(
    "/work_ai",
    "/human/video/aiAsr/point/get",
    { number}
  );
  countData.value = res
  if (countData.value?.usable != 1) {
      // 打开充值弹窗
    vipVisible.value = true
    reject('点数不足')
    return
  }
  // 获取消耗提示词内容
  const content = utils.useText(countData.value)

  try {      
    // 打开积分消耗提示
    await utils.kd({
      content,
      res:countData.value
    })
    resolve('点数足够,同意消耗')
  } catch (error) {
    reject('不同意消耗')
  }
})
}

// 重置数据
const resetData = () => {
  Object.assign(formState, getBaseFormData())
  state.textList = []
  state.baseTextList = []
  state.job_id = ''
  state.current = 0
  state.isFlod = false
  loading.value = false 
  submitLoading.value = false
}

// 下一步
const stateNext = () => {
  state.current = 1
}

const stepChange=(current)=>{
  state.current = current
}

// 步骤条 下一步的禁用逻辑
const nextDisabled =ref(true)

const nextDisabledChange=(val)=>{
  nextDisabled.value = val.length ? false : true
}



// 重置文本数据
const resetTextData = () => {
  state.textList = JSON.parse(JSON.stringify(state.baseTextList))
  nextTick(() => {
    state.textList.forEach((item, index) => {
      // 重置富文本数据
      editorRef.value[index].setContent(item?.content)
    })
  })
}

// loading 开关
const loading = ref(false)
const loadingText = ref('字幕获取中...')

  // 查询是否已经有了字幕信息
const haveVideoText = async () => {
  loading.value = true

  try {
    const res = await request.get(
    "/work_ai",
    "/human/video/video/ars/videoText",
    {
      human_video_id: state.detailItem.id,
    }
  );
    console.log(res, '是否有字幕');
    const textList = res.result?.output?.SubtitleTracks || []
    
    if(Array.isArray(textList) && textList.length) {
      setTimeout(()=>{
        state.textList = textList
        nextDisabled.value = false
        state.baseTextList = JSON.parse(JSON.stringify(state.textList))
        state.job_id = res.result?.job_id
      },10)
    }else{
      nextDisabled.value = true
    }
  } catch (error) {
    
  } finally {
    loading.value = false 
  }
}

const open = (item) => {

    // 花字列表
    getFlowerListData()
    // 字体列表
    getFontList()
    console.log(item,'字幕生成的item');
    state.detailItem = item
    haveVideoText()
    state.visible = true
}

const close = () => {
  state.visible = false
  // resetData()
}

watch(() => state.visible, (val) => {

  if (!val) {
    resetData()
  }
  
})

defineExpose({
    open,
    close
})

</script>

<template>

<a-modal v-model:visible="state.visible" title="数字人字幕生成"
wrapClassName="subtitleCreat_dialog"
width="1200px"
> 
    <IdentifySubtitles :detailItem="state.detailItem" :textList="state.textList" :fontList="state.fontList" :flowerArr="state.flowerArr" :presetStylesList="state.presetStylesList" @stepChange="stepChange" :current="state.current" :successData="successData" @successChange="successChange" @nextDisabledChange="nextDisabledChange"/>
    <template #footer>
        <div class="bottom_btns" >
          <template v-if="state.current == 1">
            <a-button type="primary" @click="handleOk" :loading="submitLoading">确定</a-button>
          </template>
          <template v-if="state.current == 0">
            <a-button type="primary" @click="stateNext" :disabled="nextDisabled"> 
              下一步</a-button>
          </template>
            <a-button @click="close">取消</a-button>
        </div>
    </template>
</a-modal>

  <!-- 充值弹窗 -->
  <vipModal :visible="vipVisible" @close="vipVisible = false"></vipModal>

  <!-- loading 遮罩 -->
  <loadingMask ref="loadingMaskRef" :text="loadingText" :zIndex="1001" :loading="loading"></loadingMask>

</template>

<style lang="less" scoped>

// 小标题字体颜色
@font_color: #42464e;
// 小图标字体大小
@font_size: 13px;

// 定制 tab的样式
:deep(.ss-tabs-nav-wrap){
.ss-tabs-nav-list{
  .ss-tabs-tab{
    padding-top: 0;
  }
}
}

.subtitleCreat_dialog{

    .subtitleCreat{
        width: 100%;
        height: 60vh;
        .content_box{
            height: 100%;
            width: 100%;
            display: flex;
            gap: 20px;
            .left_box{
                // background-color: rgba(135, 207, 235, 0.459);
                background-color: #000;
            height: 100%;
                
                .video_box{
                    height: 100%;
                    width: 400px;
                    video{
                        height: 100%;
                        width: 100%;
                    }
                }
            }

    .right_box{
        flex: 1;
        overflow-y: auto ;
        position: relative;
        &::-webkit-scrollbar {
            width: 8px; /* 滚动条的宽度 */
            height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
        }
        &::-webkit-scrollbar-thumb {
            background: #c5c5c5; /* 滑块的背景颜色 */
            border-radius: 10px; /* 滑块的圆角 */
        }

        .title_step{
          position: sticky;
          left: 0; top: 0;
          z-index: 10;
          background-color: #fff;
        }

        // 获取字幕前的状态
        .not_textList{
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .btn_controls{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
            margin-bottom: 20px;
            padding-right: 5px;
        }

        .text_list_box {
          height: 100%;
          width: 100%;
          display: flex;
          flex-direction: column;
          gap: 20px;

          .text_list_item{
            width: 100%;
            padding-right: 5px;
            .title_msg {
              display: flex;
              align-items: center;
              gap: 20px;
              .text_list_item_time{

              }
            }
            .text_list_item_title {
              color: #333;
            }
            .textarea_box{
              &::-webkit-scrollbar {
                  width: 4px; /* 滚动条的宽度 */
                  height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
              }
              &::-webkit-scrollbar-thumb {
                  background: #c5c5c5; /* 滑块的背景颜色 */
                  border-radius: 10px; /* 滑块的圆角 */
              }
            }
          }
        }
                
    .font_setting_item {
      display: flex;
      position: relative;
      align-items: center;
      margin-bottom: 20px;

    // 字体设置
    .font_setting_box {
        flex: 1;
        // max-width: 550px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-around;
        background-color: #f6f8fa;
        overflow-x: auto;
        overflow-y: hidden;

        &::-webkit-scrollbar {
          height: 4px;
          /* 滚动条的高度，垂直滚动条可能用得上 */
        }

        &::-webkit-scrollbar-thumb {
          background: #888;
          /* 滑块的背景颜色 */
          border-radius: 10px;
          /* 滑块的圆角 */
        }

        // 选择字体气泡框
        :deep(.ant-popover-inner-content) {
          padding: 0px;
        }

        // 字体大小数字input
        :deep(.ant-input-number) {
          background-color: transparent;
          border: none;
          width: 56px;
        }

        :deep(.ant-input-number-input) {
          text-align: center;
        }

        :deep(.zs-color-picker-panel) {
          margin-top: 16px;
          left: 0px;
        }

        .select_font_box {
          display: flex;
          flex-direction: column;
          height: 400px;
          overflow-y: auto;
          padding-right: 4px;

          &:hover {
            padding-right: 0;

            &::-webkit-scrollbar {
              display: block;
            }
          }

          &::-webkit-scrollbar {
            width: 4px;
            /* 滚动条的宽度 */
            height: 10px;
            /* 滚动条的高度，垂直滚动条可能用得上 */
            display: none;
          }

          &::-webkit-scrollbar-thumb {
            background: #888;
            /* 滑块的背景颜色 */
            border-radius: 10px;
            /* 滑块的圆角 */
          }

          .select_font_item {
            padding: 8px 16px;
            cursor: pointer;
            min-width: 157px;
            display: flex;
            align-items: center;
            justify-content: space-between;

            &:hover {
              background-color: #eeefef;
            }
          }

          .font_active {
            font-weight: 600;
          }
        }

        .font_settings_style {
          cursor: pointer;
          color: #0c0d0e;
          margin: 0 5px;
          padding: 3px;
          display: flex;
          align-items: center;
        //   flex: 1;
          width: 60%;
          justify-content: center;
          span {

            // max-width: 70px;
            margin-right: 5px;
            font-size: @font_size;
            // 不换行
            white-space: nowrap;
            // 省略号
            overflow: hidden;
            text-overflow: ellipsis;
          }

          &:hover {
            background-color: #eeefef;
          }
        }

        // 字体大小
        .font_settings_size {
          margin: 0 5px;
          height: 40px;
          line-height: 40px;
          display: flex;
          align-items: center;

          &:hover {
            background-color: #eeefef;
          }

          .change_btn {
            cursor: pointer;
            padding: 0 10px;
            color: @font_color;
            -webkit-user-select: none;
            /* Safari, Chrome 和 Opera */
            -moz-user-select: none;
            /* Firefox */
            -ms-user-select: none;
            /* Internet Explorer/Edge */
            user-select: none;
            /* 非前缀的版本, 应用于所有现代浏览器 */
          }
        }

        // 分割线
        .split_line {
        //   margin: 0 10px;
          height: 20px;
          width: 1px;
          background-color: #e2e2e2;
        }

        // 字体颜色和背景色
        .color_settings_box {
          display: flex;
          gap: 7px;

          .settings_color {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 7px 7px;
            position: relative;
            border-radius: 5px;
            overflow: hidden;

            &:hover {
              & .del_bgc {
                opacity: 1;
              }
            }

            .del_bgc {
              position: absolute;
              top: -5px;
              right: -5px;
              font-size: 22px;
              opacity: 0;

              &:hover {
                color: red;
              }
            }

            &:hover {
              background-color: #eeefef;
              cursor: pointer;
            }

            .color_line {
              height: 2px;
              width: 60%;
              background-color: #000;
              position: absolute;
              bottom: 0px;
              left: calc(50% - 30%);
            }
          }
        }

        // 字体粗细倾斜和排列方式
        .font_settings_style_control {
          display: flex;
          align-items: center;
          gap: 10px;

          // 设置气泡框样式
          :deep(.ant-popover-inner-content) {
            padding: 0px;
          }

          .select_alignment {
            display: flex;

            span {
              padding: 5px;
              cursor: pointer;

              &:hover {
                background-color: #eeefef;
              }
            }

            .active_alignment {
              background-color: #eeefef;
            }
          }

          .font_settings_style_itme {
            padding: 2px 7px;
            cursor: pointer;
            border-radius: 5px;
            overflow: hidden;

            &:hover {
              background-color: #eeefef;
            }
          }

          .is_active {
            background-color: #d8e7fc !important;
          }

          .alignment {
            display: flex;
            padding: 4px;
          }
        }
      }


      .font_style_title{
        color: @font_color;
        font-size: @font_size;
        padding-right: 15px;
        display: flex;
        // justify-content: start;
        align-self: flex-start;
        // 一行显示
        white-space: nowrap;
    }

    // 花字设置
    .font_style_box {

.font_style_content_box {
overflow-y: auto;
display: flex;
flex-wrap: wrap;
gap: 10px;
overflow: hidden;



.font_style_content_item {
border: 2px solid #ededee;
cursor: pointer;
border-radius: 8px;
overflow: hidden;

.font_img{
    width: 200px;
    height: 51px;
    object-fit: contain;
}

&:hover {
    border-color: #1664ff;
    background-color: #e8f7ff;
}

.font_style_content_item_text {
    width: 51px;
    font-size: 20px;
    line-height: 51px;
    text-align: center;
    margin: 0;
    font-weight: 900;
}
}

.active_font_style {
border-color: #1664ff;
}
}

// 禁用
.font_disabled {
width: 51px;
font-size: 32px;
text-align: center;
}


// 折叠按钮
.folding_panel {
color: #737a87;
text-align: center;
width: 100%;
display: block;
cursor: pointer;
margin-top: 15px;
}
    }
    }
                



            }

        }
    }
}

</style>